package com.quxing.amazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.quxing.amazon.mapper.GoodMapper;
import com.quxing.amazon.model.Category;
import com.quxing.amazon.model.Good;
import com.quxing.amazon.model.dto.GoodQuery;
import com.quxing.amazon.model.vo.GoodVO;
import com.quxing.amazon.service.CategoryService;
import com.quxing.amazon.service.GoodService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 亚马逊商品 服务实现类
 * </p>
 *
 * @author zhb
 * @since 2021-05-09
 */
@SuppressWarnings("Duplicates")
@Service
@RequiredArgsConstructor
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements GoodService {

    private final CategoryService categoryService;

    @Override
    public PageInfo<GoodVO> pageByQuery(GoodQuery goodQuery) {
        Integer categoryId = goodQuery.getCategoryId();
        if (categoryId != null) {
            goodQuery.setCategoryIds(categoryService.getAllChildrenIdsByCategoryId(categoryId, new ArrayList<>()));
        }
        PageHelper.startPage(goodQuery.getPage(), goodQuery.getSize());
        List<GoodVO> goodVOS = this.baseMapper.listByQuery(goodQuery);
        //填充分类
        if (goodVOS.size() > 0) {
            List<Integer> categoryIds = goodVOS.stream()
                    .map(GoodVO::getCategoryId)
                    .collect(Collectors.toList());
            LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery().in(Category::getId, categoryIds);
            List<Category> categories = categoryService.list(wrapper);
            Map<Integer, Category> categoryMap = categories.stream()
                    .collect(Collectors.toMap(Category::getId, v -> v));
            goodVOS.forEach(goodVO -> {
                Category category = categoryMap.get(goodVO.getCategoryId());
                goodVO.setCategoryName(category == null ? "未知分类" : category.getName());
            });
        }
        return new PageInfo<>(goodVOS);
    }

    @Override
    public Integer getLastOneGoodCategory() {
        return this.baseMapper.getLastOneGoodCategory();
    }

    @Override
    public List<Integer> selectCategoryIds() {
        return this.baseMapper.selectCategoryIds();
    }
}
